import json  # 导入json模块，用于处理JSON格式数据
import math  # 导入math模块，用于数学运算
import sys  # 导入sys模块，用于与Python解释器交互

total_items = 0
word_freq = {}  # 初始化一个空字典，用于存储词组频率
# 读取字符到拼音的映射关系
char_pinyin_map = {}  # 初始化一个空字典，用于存储字符到拼音的映射
char_pinyin_data = {}
word_pinyin_data = {}
char_frequency = {}  # 存储字符出现频率
pinyin_total_counts = {}  # 存储拼音总次数

def reverse_output_stack(stack, levels):
    for i in range(levels):
        print(stack.pop(), end='')
    print()

def get_word_position(word):
    return word_freq[word] if word in word_freq else 0

def calculate_transition_probability(char_prev, char_curr):
    combined_word = f'{char_prev} {char_curr}'  # 构造由两个字符组成的词
    transition_prob = get_word_position(combined_word) / char_frequency[char_prev]  # 计算转移概率
    return 0.95 * transition_prob + 0.05 * char_frequency[char_curr] / total_items  # 返回平滑后的概率

# 定义函数solve，用于根据拼音序列推断最可能的汉字序列
def process_pinyin_sequence(pinyin_list, sequence_length):
    dp_table = {i: {char: 100861008610086 for char in char_pinyin_data.get(pinyin_list[i], {}).get("words", [])} for i in range(sequence_length)}
    predecessor_table = {i: {char: None for char in char_pinyin_data.get(pinyin_list[i], {}).get("words", [])} for i in range(sequence_length)}
    min_value = 100861008610086
    final_char = None

    for i in range(sequence_length):
        for current_char in char_pinyin_data.get(pinyin_list[i], {}).get("words", []):  # 遍历当前拼音对应的汉字
            if i == 0:  # 如果是第一个拼音
                dp_table[i][current_char] = -math.log(char_frequency[current_char] / pinyin_total_counts[pinyin_list[0]])  # 计算初始概率
            elif i == sequence_length - 1:  # 如果是最后一个拼音
                for previous_char in char_pinyin_data.get(pinyin_list[sequence_length - 2], {}).get("words", []):  # 遍历前一个拼音对应的汉字
                    if dp_table[sequence_length - 2][previous_char] - math.log(calculate_transition_probability(previous_char, current_char)) < dp_table[sequence_length - 1][current_char]:
                        dp_table[sequence_length - 1][current_char] = dp_table[sequence_length - 2][previous_char] - math.log(calculate_transition_probability(previous_char, current_char))
                        if dp_table[sequence_length - 1][current_char] < min_value:
                            min_value = dp_table[sequence_length - 1][current_char]
                            final_char = current_char
                        predecessor_table[sequence_length - 1][current_char] = previous_char
            else:
                for previous_char in char_pinyin_data.get(pinyin_list[i - 1], {}).get("words", []):  # 遍历前一个拼音对应的汉字
                    if dp_table[i - 1][previous_char] - math.log(calculate_transition_probability(previous_char, current_char)) < dp_table[i][current_char]:
                        dp_table[i][current_char] = dp_table[i - 1][previous_char] - math.log(calculate_transition_probability(previous_char, current_char))
                        predecessor_table[i][current_char] = previous_char

    char_stack = []
    char_stack.append(final_char)
    for i in range(sequence_length - 1, 0, -1):
        char_stack.append(predecessor_table[i][char_stack[-1]])
    reverse_output_stack(char_stack, sequence_length)  # 反转并打印结果列表

if __name__ == '__main__':
    try:
        with open('./word2pinyin.txt', 'r', encoding='utf-8') as file:
            for line in file:
                segments = line.split()
                char_pinyin_map[segments[0]] = segments[1]  # 将字符映射到拼音
    except FileNotFoundError:
        print(f"File not found:'./word2pinyin.txt'")
    except Exception as e:
        print(f"An error occurred: {e}")

    try:
        with open('./1_word.txt', 'r', encoding='utf-8') as file:
            char_pinyin_data = json.load(file)
    except FileNotFoundError:
        print(f"File not found:'./1_word.txt'")
    except Exception as e:
        print(f"An error occurred: {e}")

    try:
        with open('./2_word.txt', 'r', encoding='utf-8') as file:
            word_pinyin_data = json.load(file)
    except FileNotFoundError:
        print(f"File not found:'./2_word.txt'")
    except Exception as e:
        print(f"An error occurred: {e}")

    for pinyin_key, data in char_pinyin_data.items():
        pinyin_total_counts[pinyin_key] = sum(data.get('counts', []))
        for element, count in zip(data.get('words', []), data.get('counts', [])):
            char_frequency[element] = count

    total_items = sum(pinyin_total_counts.values())

    for data in word_pinyin_data.values():
        elements = data.get('words', [])
        counts = data.get('counts', [])
        for element, count in zip(elements, counts):
            word_freq[element] = count

    while True:
        user_input = sys.stdin.readline()
        if user_input == "":
            break
        else:
            process_pinyin_sequence(user_input.split(), len(user_input.split()))